package com.caocao.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 描述:http请求AOP切面类
 *
 * @Author:操文健
 * @Create Time:2017-09-10 4:00
 */
@Aspect
@Component
public class HttpAspect {

    // log进行日志记录
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    // 设置相关切入点
    @Pointcut("execution(public  * com.caocao.controller.*.*(..))")
    public void  pointCut(){
    }

    @Before("pointCut()")
    public  void controllerDoBefore(JoinPoint point) {
        logger.info("进入控制器方法中开始进行执行...");
        // 获取请求属性信息
        ServletRequestAttributes attributes = (ServletRequestAttributes)  RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // URL
        logger.info("url = {}", request.getRequestURL());
        //Method
        logger.info("method = {}", request.getMethod());
        //IP
        logger.info("IP = {}", request.getRemoteAddr());
        //类方法
        logger.info("class_method = {}", point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName());
        //参数
        logger.info("arge = {}", point.getArgs());
    }

    @After("pointCut()")
    public  void controllerDoAfter() {
        logger.info("控制器方法执行完成后的处理...");
    }

    // 获取返回结果的切面处理
    @AfterReturning(returning = "object", pointcut = ("pointCut()"))
    public void controllerDoArterReturn(Object object) {
        logger.info("response = {}", object.toString());
    }
}
